import { createRouter, createWebHistory } from "vue-router";
import { useUserStore } from "../stores/user";

const routes = [
  {
    path: "/",
    name: "Layout",
    component: () => import("../layout/index.vue"),
    redirect: "/home",
    children: [
      {
        path: "home",
        name: "Home",
        component: () => import("../views/home/index.vue"),
        meta: {
          title: "首页",
          icon: "HomeFilled",
        },
      },
      {
        path: "dashboard",
        name: "Dashboard",
        component: () => import("../views/dashboard/index.vue"),
        meta: {
          title: "仪表盘",
          icon: "Odometer",
        },
      },
      {
        path: "basic",
        name: "Basic",
        component: () => import("../views/basic/index.vue"),
        meta: {
          title: "基础管理",
          icon: "Setting",
        },
        children: [
          {
            path: "employee",
            name: "Employee",
            component: () => import("../views/basic/employee/index.vue"),
            meta: {
              title: "员工管理",
            },
          },
          {
            path: "resource",
            name: "Resource",
            component: () => import("../views/basic/resource/index.vue"),
            meta: {
              title: "资源管理",
            },
          },
          {
            path: "role",
            name: "Role",
            component: () => import("../views/basic/role/index.vue"),
            meta: {
              title: "角色管理",
            },
          },
          {
            path: "employee-role",
            name: "EmployeeRole",
            component: () => import("../views/basic/employee-role/index.vue"),
            meta: {
              title: "员工角色",
            },
          },
          {
            path: "application",
            name: "Application",
            component: () => import("../views/basic/application/index.vue"),
            meta: {
              title: "应用管理",
            },
          },
        ],
      },
    ],
  },
  {
    path: "/login",
    name: "Login",
    component: () => import("../views/login/index.vue"),
    meta: {
      title: "登录",
    },
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
});

// 全局前置守卫
router.beforeEach(async (to, from, next) => {
  // 设置页面标题
  document.title = to.meta.title ? `后台管理系统 - ${to.meta.title}` : '后台管理系统';
  
  const userStore = useUserStore();
  const token = userStore.token;
  
  // 判断是否有token
  if (token) {
    if (to.path === '/login') {
      // 如果已登录，跳转到首页
      next({ path: '/' });
    } else {
      // 判断是否已获取用户信息
      if (Object.keys(userStore.userInfo).length === 0) {
        try {
          // 获取用户信息
          await userStore.getUserPermissions();
          next();
        } catch (error) {
          // 获取用户信息失败，可能是token过期，清空token并跳转到登录页
          userStore.logout();
          next(`/login?redirect=${to.path}`);
        }
      } else {
        // 已有用户信息，直接放行
        // 每次路由切换时刷新权限
        userStore.getUserPermissions();
        next();
      }
    }
  } else {
    // 没有token
    if (to.path === '/login') {
      // 如果是登录页，直接放行
      next();
    } else {
      // 如果不是登录页，跳转到登录页
      next(`/login?redirect=${to.path}`);
    }
  }
});

export default router;
